package com.cherry.javaee.demo.dao.impl;

import com.cherry.javaee.demo.dao.IUserDao;
import com.cherry.javaee.demo.domain.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao1")
public class UserDao1Impl implements IUserDao {

    @Autowired
    private QueryRunner mRunner;

    //bean.xml专用
//    public void setmRunner(QueryRunner mRunner) {
//        this.mRunner = mRunner;
//    }

    public List<User> findAllUser() {
        try {
            return mRunner.query("select * from test_user", new BeanListHandler<User>(User.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public User findUser(Long id) {
        try {
            return mRunner.query("select * from test_user where id=?", new BeanHandler<User>(User.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveUser(User user) {
        try {
            mRunner.update("insert into test_user(name,password)values(?,?)", user.getName(), user.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void update(User user) {
        try {
            mRunner.update("update test_user set name=?,password=? where id=?", user.getName(), user.getPassword(), user.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteUser(Long id) {
        try {
            mRunner.update("delete from test_user where id=?", id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
